package com.durian.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jackson.JsonComponent;

import java.io.IOException;

/**
 * 长整型序列化配置，防止前端精度丢失
 *
 * @author Durian
 * @since 2023/12/4
 */
@JsonComponent
public class LongSerializerConfig extends JsonSerializer<Long> {

    @Value("${spring.jackson.longAsString}")
    private Boolean longAsString;

    @Override
    public void serialize(Long aLong, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (longAsString) {
            jsonGenerator.writeString(String.valueOf(aLong));
        } else {
            jsonGenerator.writeNumber(aLong);
        }
    }

}
